package com.fzt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzt.reggie.common.R;
import com.fzt.reggie.dto.DishDto;
import com.fzt.reggie.entity.Category;
import com.fzt.reggie.entity.Dish;
import com.fzt.reggie.entity.DishFlavor;
import com.fzt.reggie.entity.Employee;
import com.fzt.reggie.service.CategoryService;
import com.fzt.reggie.service.DishFavorService;
import com.fzt.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishFavorService dishFavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    /*
    新增菜品功能
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增成功");
    }

    /*
    菜品管理分页
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //构造查询条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);

        //排序条件
        qw.orderByDesc(Dish::getUpdateTime);
        //查询结果
        dishService.page(dishPage,qw);

        //拷贝Page对象属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map(item ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = dishDto.getCategoryId();
            //根据categoryIdchaz类别数据库
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /*
    根据id查询菜品信息
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = new DishDto();
        //根据id查询Dish表，获得Dish相关数据
        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish,dishDto);

        //再根据dishId查询口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @PutMapping
    //@Transactional
    public R<String> update(@RequestBody DishDto dishDto){
        //需要更新两张表
        //根据Dish的id更新dish表
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }



    /*public R<List<Dish>> categoryList(@PathVariable Long categoryId){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        //查询在售的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    /*
    通过categoryId查询与其关联的dish表中的菜品
     */
   @GetMapping("/list")
   public R<List<DishDto>> list(Dish dish){
       //构造查询条件
       LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
       //添加条件，查询状态为1（起售状态）的菜品
       queryWrapper.eq(Dish::getStatus,1);

       //添加排序条件
       queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

       List<Dish> list = dishService.list(queryWrapper);

       List<DishDto> dishDtoList = list.stream().map((item) -> {
           DishDto dishDto = new DishDto();

           BeanUtils.copyProperties(item,dishDto);

           Long categoryId = item.getCategoryId();//分类id
           //根据id查询分类对象
           Category category = categoryService.getById(categoryId);

           if(category != null){
               String categoryName = category.getName();
               dishDto.setCategoryName(categoryName);
           }

           //当前菜品的id
           Long dishId = item.getId();
           LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
           lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
           //SQL:select * from dish_flavor where dish_id = ?
           List<DishFlavor> dishFlavorList = dishFavorService.list(lambdaQueryWrapper);
           dishDto.setFlavors(dishFlavorList);
           return dishDto;
       }).collect(Collectors.toList());

       return R.success(dishDtoList);
   }

}
